package service

import (
	"context"
	"fmt"
	"github.com/beherochuling/beesoft_api/app/dao"
	"github.com/beherochuling/beesoft_api/app/helper/software/software"
	"github.com/beherochuling/beesoft_api/app/model/entity"
	"github.com/beherochuling/beesoft_api/app/model/task"
	"github.com/gogf/gf/v2/os/glog"
)

var Setting = settingService{}

type settingService struct{}

// Gets 获取多个配置-无缓存
func (settingService) Gets(ctx context.Context, keys []string) map[string]string {
	var settings []entity.Settings
	err := dao.Settings.Ctx(ctx).
		WhereIn(dao.Settings.Columns().Key, keys).
		Scan(&settings)
	if err != nil {
		panic(err)
	}

	data := map[string]string{}
	for _, setting := range settings {
		data[setting.Key] = setting.Value
	}

	return data
}

// Get 获取单个配置
func (settingService) Get(ctx context.Context, key string) string {
	cacheKey := fmt.Sprintf(task.CacheKeySettings, key)
	cacheValue, err := software.Redis(ctx).Get(cacheKey)
	if err != nil {
		glog.Warningf(ctx, "%+v", err)
		// panic(err)
	}

	var value string

	if cacheValue == nil {
		var item entity.Settings

		err := dao.Settings.Ctx(ctx).
			WhereIn(dao.Settings.Columns().Key, key).
			Scan(&item)
		if err != nil {
			panic(err)
		}

		value = item.Value

		_, err = software.Redis(ctx).Set(cacheKey, value)
		if err != nil {
			panic(err)
		}
	} else {
		value = cacheValue.String()
	}

	return value
}
